/**
 * Created by shuan on 2016/11/29.
 */
//初始化日期插件
//var palette = ["#d7d7cd", "#50bebe", "#aaaa96", "#009999", "#73645a", "#41aaaa", "#00646e", "#879baa", "#009999", "#879baa", "#2d373c", "#73645a", "#c8c8b9", "#3c464b", "#4b3c32", "#cdd9e1"];
var palette = ["#41aaaa","#647d2d","#73645a","#adbecb","#641946","#50bed7"];
$(function () {
    $("#dOrsState_getDay").datepicker({
        language: "zh-CN",
        autoclose: true,
        format: "yyyy-mm-dd",
        startDate: new Date("2016-11-01"),
        endDate: new Date(dateAddSubtract(new Date(), -1)),
        todayHighlight:true
    }).on('changeDate', function (ev) {
        getShifts();
    });

    $("#dsfrt_getDay").datepicker({
        language: "zh-CN",
        autoclose: true,
        format: "yyyy-mm-dd",
        startDate: new Date("2016-11-01"),
        endDate: new Date(dateAddSubtract(new Date(), -1)),
        todayHighlight:true
    }).on("changeDate", function () {
        getShifts();
    });

    $("#service_shift_getDate").datepicker({
        language: "zh-CN",
        autoclose: true,
        format: "yyyy-mm-dd",
        startDate: new Date("2016-11-01"),
        endDate: new Date(dateAddSubtract(new Date(), -1)),
        todayHighlight:true
    }).on("changeDate", function () {
        if (deviceUpdate == false) {
            indexServicesShiftLineChart(null, null);
        } else {
            deviceUpdate = false;
        }
    });

    $(".radio").click(function () {
        $(this).parent().find(".selected").removeClass("selected");
        $(this).addClass("selected");
        if ($(this).parent()[0].id == "indexparam") {
            $("#service_start_time").val("");
            $("#service_end_time").val("");
            $("#service_start_time").datepicker("update");
            $("#service_end_time").datepicker("update");
            indexServicesLineChart(null, null);
        } else if ($(this).parent()[0].id == "indexParamShift") {
            $("#service_shift_getDate").val("");
            $("#service_shift_getDate").datepicker("update");
            indexServicesShiftLineChart(null, null);
        }
    });
});

//生成折线图：同机床不同原因
function createSameDeviceDiffReasonLineChart(dataSource, series) {
    $("#sameDeviceDiffReasonLineChat").dxChart({
        palette: palette,
        dataSource: dataSource,
        commonSeriesSettings: {
            argumentField: "date",
            type: "line"
        },
        margin: {
            bottom: 20
        },
        argumentAxis: {
            valueMarginsEnabled: false,
            discreteAxisDivisionMode: "crossLabels",
            grid: {
                visible: true
            }
        },
        valueAxis: {
            label: {
                format: function (value) {
                    return secondToDate(value);
                }
            }
        },
        series: series,
        legend: {
            verticalAlignment: "top",
            horizontalAlignment: "right",
            itemTextPosition: "top",
            position:"Outside"
        },
        "export": {
            enabled: false
        },
        tooltip: {
            enabled: true,
            customizeTooltip: function (arg) {
                return {
                    text: secondToDate(arg.valueText)
                };
            }
        }
    }).dxChart("instance");

    $("#rangeSelector").dxRangeSelector({
        size: {
            height: 60
        },
        margin: {
            left: 10
        },
        scale: {
            minorTickCount: 1
        },
        dataSource: dataSource,
        chart: {
            commonSeriesSettings: {
                argumentField: "date",
                type: "line"
            },
            series: series,
            palette: palette
        },
        behavior: {
            callSelectedRangeChanged: "onMoving"
        },
        onSelectedRangeChanged: function (e) {
            var zoomedChart = $("#sameDeviceDiffReasonLineChat").dxChart("instance");
            zoomedChart.zoomArgument(e.startValue, e.endValue);
        }
    })
}

//生成折线图：同机床同原因
function createSameDeviceSameReasonLineChart(dataSource, series) {
    $("#sameDeviceSameReasonLineChat").dxChart({
        palette: palette,
        dataSource: dataSource,
        commonSeriesSettings: {
            argumentField: "date",
            type: "line"
        },
        margin: {
            bottom: 20
        },
        argumentAxis: {
            valueMarginsEnabled: false,
            discreteAxisDivisionMode: "crossLabels",
            grid: {
                visible: true
            }
        },
        valueAxis: {
            label: {
                format: function (value) {
                    return secondToDate(value);
                }
            }
        },
        series: series,
        legend: {
            verticalAlignment: "top",
            horizontalAlignment: "right",
            itemTextPosition: "top",
            position:"Outside"
        },
        "export": {
            enabled: false
        },
        tooltip: {
            enabled: true,
            customizeTooltip: function (arg) {
                return {
                    text: secondToDate(arg.valueText)
                };
            }
        }
    }).dxChart("instance");

    $("#rangeSelector").dxRangeSelector({
        size: {
            height: 60
        },
        margin: {
            left: 10
        },
        scale: {
            minorTickCount: 1
        },
        dataSource: dataSource,
        chart: {
            commonSeriesSettings: {
                argumentField: "date",
                type: "line"
            },
            series: series,
            palette: palette
        },
        behavior: {
            callSelectedRangeChanged: "onMoving"
        },
        onSelectedRangeChanged: function (e) {
            var zoomedChart = $("#sameDeviceSameReasonLineChat").dxChart("instance");
            zoomedChart.zoomArgument(e.startValue, e.endValue);
        }
    });
}

//生成折线图：同原因全部机床折线图
function createSameReasonDevicesLineChart(dataSource, series) {
    $("#sameReasonDeviceLineChat").dxChart({
        palette: palette,
        dataSource: dataSource,
        commonSeriesSettings: {
            argumentField: "date",
            type: "line"
        },
        margin: {
            bottom: 20
        },
        argumentAxis: {
            valueMarginsEnabled: false,
            discreteAxisDivisionMode: "crossLabels",
            grid: {
                visible: true
            }
        },
        valueAxis: {
            label: {
                customizeText: function (arg) {
                    //return this.value + '%';
                    return secondToDate(this.value);
                }
            }
        },
        series: series,
        legend: {
            verticalAlignment: "top",
            horizontalAlignment: "right",
            itemTextPosition: "top",
            position:"Outside"
        },
        "export": {
            enabled: false
        },
        tooltip: {
            enabled: true,
            customizeTooltip: function (arg) {
                return {
                    text: secondToDate(arg.valueText)
                };
            }
        },
        onPointClick: function (e) {
            var point = e.target;

            toggleVisibility(point);
        },
        onLegendClick: function (e) {
            var arg = e.target;

            toggleVisibility(arg);
        }
    }).dxChart("instance");
    function toggleVisibility(item) {
        item.isVisible() ? item.hide() : item.show();
    }
    $("#rangeSelector").dxRangeSelector({
        size: {
            height: 60
        },
        margin: {
            left: 10
        },
        scale: {
            minorTickCount: 1
        },
        dataSource: dataSource,
        chart: {
            commonSeriesSettings: {
                argumentField: "date",
                type: "line"
            },
            series: series,
            palette: palette
        },
        behavior: {
            callSelectedRangeChanged: "onMoving"
        },
        onSelectedRangeChanged: function (e) {
            var zoomedChart = $("#sameReasonDeviceLineChat").dxChart("instance");
            zoomedChart.zoomArgument(e.startValue, e.endValue);
        }
    });
}

//生成折线图：oee或performance或quality或availability indexParam趋势
function createIndexServicesLineChart(dataSource, series, subTitle) {
    $("#serviceLine").dxChart({
        dataSource: dataSource,
        commonSeriesSettings: {
            argumentField: "time",
            type: "line"
        },
        margin: {
            bottom: 20
        },
        argumentAxis: {
            label: {
                format: "date"
            },
            valueType: "date",
            valueMarginsEnabled: false,
            discreteAxisDivisionMode: "crossLabels",
            grid: {
                visible: true
            }
        },
        valueAxis: {
            label: {
                format: function (value) {
                    return parseInt(value * 100) + "%";
                }
            }
        },
        series: series,
        palette: palette,
        legend: {
            verticalAlignment: "top",
            horizontalAlignment: "right",
            itemTextPosition: "top",
            position:"Outside"
        },
        title: {
            text: " ",
            subtitle: {
                text: subTitle,
                font:{
                    size:14
                }
            }
        },
        "export": {
            enabled: false
        },
        tooltip: {
            enabled: true,
            customizeTooltip: function (arg) {
                return {
                    text: (arg.valueText * 100).toFixed(2) + "%"
                };
            }
        }
    }).dxChart("instance");

    $("#rangeSelector").dxRangeSelector({
        size: {
            height: 60
        },
        margin: {
            left: 10
        },
        scale: {
            minorTickCount: 1
        },
        dataSource: dataSource,
        chart: {
            commonSeriesSettings: {
                argumentField: "time",
                type: "line"
            },
            series: series,
            palette: palette
        },
        behavior: {
            callSelectedRangeChanged: "onMoving"
        },
        onSelectedRangeChanged: function (e) {
            var zoomedChart = $("#serviceLine").dxChart("instance");
            zoomedChart.zoomArgument(e.startValue, e.endValue);
        }
    })
}

//生成平线图：某天全部班次 oee或performance或quality或availability indexParam趋势
function createIndexServicesShiftLineChart(dataSource, series, type) {
    $("#serviceShiftLine").dxChart({
        title: "Australian Olympic Medal Count",
        dataSource: dataSource,
        commonSeriesSettings: {
            type: "stepline",
            argumentField: "time",
            stepline: {
                point: {
                    visible: true
                }
            }
        },
        series: series,
        argumentAxis: {
            label: {
                format: "hour"
            },
            valueType: "datetime",
            type: "Continuous",
        },
        valueAxis: {
            label: {
                format: function (value) {
                    return parseInt(value) + "%";
                }
            }
        },
        "export": {
            enabled: false
        },
        legend: {
            verticalAlignment: "bottom",
            horizontalAlignment: "center"
        },
        tooltip: {
            enabled: true,
            customizeTooltip: function (arg) {
                return {
                    text: (arg.valueText).toFixed(2) + "%"
                };
            }
        }
    });
}
/*
 //生成柱状图：一台机床的状态时间统计的历史趋势
 function createOneDeviceStateBarChart(dataSource){
 $("#oneOrMoreDeviceStateBarChat").dxChart({
 dataSource: dataSource,
 commonSeriesSettings: {
 argumentField: "day",
 type: "fullStackedBar"
 },
 series: [
 {valueField: "online", name: "在线"},
 {valueField: "offline", name: "离线"}
 ],
 legend: {
 verticalAlignment: "bottom",
 horizontalAlignment: "center",
 itemTextPosition: "right"
 },
 title: {
 text: "一台机床的状态时间统计的历史趋势",
 subtitle: {
 text: "(Millions of Tons, Oil Equivalent)"
 }
 },
 "export": {
 enabled: false
 },
 tooltip: {
 enabled: true,
 customizeTooltip: function (arg) {
 return {
 text: arg.percentText + " - " + arg.valueText
 };
 }
 }
 });
 }

 //生成柱状图：多台机床的状态时间统计的历史趋势
 function createMoreDeviceStateBarChart(dataSource,series){
 $("#oneOrMoreDeviceStateBarChat").dxChart({
 dataSource: dataSource,
 commonSeriesSettings: {
 argumentField: "day",
 type: "fullStackedBar"
 },
 series: series,
 legend: {
 verticalAlignment: "bottom",
 horizontalAlignment: "center"
 },
 title: "多台机床的状态时间统计的历史趋势",
 "export": {
 enabled: true
 },
 tooltip: {
 enabled: true,
 customizeTooltip: function (arg) {
 return {
 text: arg.percentText + " - " + arg.valueText
 };
 }
 }
 });
 }*/

//生成柱状图：机床的状态时间统计的历史趋势
function createDeviceStateBarChart(dataSource, series, title) {
    $("#oneOrMoreDeviceStateBarChat").dxChart({
        dataSource: dataSource,
        commonSeriesSettings: {
            argumentField: "date_id",
            type: "fullStackedBar"
        },
        series: series,
        legend: {
            verticalAlignment: "bottom",
            horizontalAlignment: "center"
        },
        title: title,
        "export": {
            enabled: false
        },
        tooltip: {
            enabled: true,
            customizeTooltip: function (arg) {
                if (arg.seriesName.indexOf("离线") > -1) {
                    return {
                        text: arg.argument + " " + arg.seriesName.split("离线")[0] + " " + "offLine time:" + secondToDate(arg.value)
                    };
                } else if (arg.seriesName.indexOf("在线") > -1) {
                    return {
                        text: arg.argument + " " + arg.seriesName.split("在线")[0] + " " + "onLine time:" + secondToDate(arg.value)
                    };
                }
            }
        }
    });

    $("#rangeSelector").dxRangeSelector({
        size: {
            height: 60
        },
        margin: {
            left: 10
        },
        scale: {
            minorTickCount: 1
        },
        dataSource: dataSource,
        chart: {
            commonSeriesSettings: {
                argumentField: "date_id",
                type: "fullStackedBar"
            },
            series: series,
            palette: "Harmony Light"
        },
        behavior: {
            callSelectedRangeChanged: "onMoving"
        },
        onSelectedRangeChanged: function (e) {
            var zoomedChart = $("#oneOrMoreDeviceStateBarChat").dxChart("instance");
            zoomedChart.zoomArgument(e.startValue, e.endValue);
        }
    })
}

//并生成饼图：24小时不同班次空闲原因总体分布
function createDayShiftFreeReasonTotalPieChart(dataSource, subTitle, title) {
    $("#shiftFreeReasonTotalPieChart").dxPieChart({
        palette: palette,
        dataSource: dataSource,
        series: [
            {
                argumentField: "reason",
                valueField: "time",
                label: {
                    visible: true,
                    connector: {
                        visible: true,
                        width: 1
                    },
                    format: function (value) {
                        return secondToDate(value);
                    }
                }
            }
        ],
        legend: {
            verticalAlignment: "bottom",
            horizontalAlignment: "center"
        },
        title: {
            text: " ",
            subtitle: {
                text: subTitle,
                font:{
                    size:14
                }
            }
        },
        "export": {
            enabled: false
        }
    });

    function toggleVisibility(item) {
        item.isVisible() ? item.hide() : item.show();
    }
}

//生成饼图：一天或班次状态信息
function createDayOrShiftStatePieChart(dataSource,title,hint1,hint2,hint3){
    $("#dayOrShiftStatePieChart").dxPieChart({
        dataSource: dataSource,
        series: [
            {
                argumentField: "state",
                valueField: "time",
                label: {
                    visible: true,
                    connector: {
                        visible: true,
                        width: 1
                    },
                    format: function (value) {
                        return secondToDate(value);
                    }
                }
            }
        ],
        legend: {
            verticalAlignment: "bottom",
            horizontalAlignment: "center",
            customizeText:function(arg){
                var legendName = arg.pointName;
                if(legendName ==1){
                    return hint1;
                }else if (legendName == 0){
                    return hint2;
                }else {
                    return hint3;
                }
            }
        },
        palette: palette,
        title: title,
        "export": {
            enabled: false
        }
    });
}

//生成饼图：一天机床状态
function createDayWorkStatePieChart(dataSource) {
    $("#workStatePieChart").dxPieChart({
        palette: palette,
        dataSource: dataSource,
        series: [
            {
                argumentField: "state",
                valueField: "time",
                label: {
                    visible: true,
                    connector: {
                        visible: true,
                        width: 1
                    },
                    format: function (value) {
                        return (value / 86400 * 100).toFixed(2) + '%';
                    }
                }
            }
        ],
        legend: {
            verticalAlignment: "bottom",
            horizontalAlignment: "center"
        },
        title: " ",
        "export": {
            enabled: false
        }
    });
}

//生成柱状图：一台机床某天idle原因状态
function createDayIdleReasonBarChart(dataSource) {
    $("#idleReasonBarChart").dxChart({
        dataSource: dataSource,
        series: {
            argumentField: "idle",
            valueField: "time",
            valueAxis: {
                label: {
                    format: function (value) {
                        return value.toFixed(2) + "%";
                    }
                }
            },
            type: "bar"
        },
        "export": {
            enabled: false
        },
        title: " ",
        legend: {
            verticalAlignment: "bottom",
            horizontalAlignment: "center"
        },
        tooltip: {
            enabled: true,
            customizeTooltip: function (arg) {
                return {
                    text: arg.value.toFixed(2) + "%"
                };
            }
        }
    });
}

//生成柱状图：维修MTTR柱状图
function createMttrBarChart(dataSource, series) {
    $("#mttrBarChart").dxChart({
        dataSource: dataSource,
        series: series,
        "export": {
            enabled: false
        },
        title: "MTTR(Hours)",
        legend: {
            verticalAlignment: "bottom",
            horizontalAlignment: "center"
        },
        tooltip: {
            enabled: true,
            customizeTooltip: function (arg) {
                return {
                    text: arg.value
                };
            }
        }
    });
}

//生成平线图：某天全部班次 oee或performance或quality或availability indexParam趋势    New
function createIndexServicesShiftLineChartNew(dataSource, type, title, hint1, hint2) {
    Highcharts.stockChart('serviceShiftLine', {
        chart: {
            marginLeft: 60
        },
        global: {
            useUTC: false
        },
        rangeSelector: {
            selected: 1
        },
        legend: {
            enabled: true,
            align: 'center'
        },
        plotOptions: {
            series: {
                marker: {
                    enabled: true,
                    symbol: 'circle',
                    radius: 4
                },
                step: true,
                tooltip: {
                    valueDecimals: 2
                }
            }
        },
        rangeSelector: {     //选择工具使用
            enabled: false
        },
        scrollbar: {
            enabled: false
        },
        navigator: {     //导航器
            enabled: false
        },
        exporting: {
            enabled: false
        },
        colors:palette,
        xAxis: {
            type: 'datetime',
            dateTimeLabelFormats: {
                hour: '%H:%M'

            }
        },
        yAxis: {
            labels: {
                formatter: function () {
                    return parseInt(this.value) + '%';
                }
            },
            opposite: false
        },
        title: {
            text: title
        },
        series: dataSource,
        tooltip: {
            enabled: true,
            formatter: function (arg) {
                return hint1 + this.points[0].series.name + " " + new Date(this.x - 28800000).getHours() + hint2 + "<br/>" + type + "：" + this.y + "%";
            }
        }
    });
}

//生成平线图：某天全部班次 oee或performance或quality或availability indexParam趋势    New
function createShiftServicesLineChartNew(dataSource,series, type, title, hint1, hint2) {
    $("#serviceShiftLine").dxChart({
        dataSource: dataSource,
        commonSeriesSettings: {
            argumentField: "time",
            type: "line"
        },
        margin: {
            bottom: 20
        },
        argumentAxis: {
            label: {
                format: "date",
                customizeText:function(){
                    return this.value.split(" ")[1].substring(0,5);
                }
            },
            valueType: "date",
            valueMarginsEnabled: false,
            discreteAxisDivisionMode: "crossLabels",
            grid: {
                visible: true
            }
        },
        valueAxis: {
            label: {
                format: function (value) {
                    return parseInt(value * 100) + "%";
                }
            }
        },
        series: series,
        palette: palette,
        legend: {
            verticalAlignment: "top",
            horizontalAlignment: "right",
            itemTextPosition: "top",
            position:"Outside"
        },
        title: {
            text: title
        },
        "export": {
            enabled: false
        },
        tooltip: {
            enabled: true,
            customizeTooltip: function (arg) {
                return {
                    html: '<div style="text-align:left"><span style="color: #009999;font-size: 12px;font-weight: 600;">'+ hint1 +'：</span>'+arg.seriesName + '</div><div><span style="color: #009999;font-size: 12px;font-weight: 600;">'+ hint2 +'：</span>' + arg.originalArgument + '</div><div><span style="color: #009999;font-size: 12px;font-weight: 600;">' + type + '：</span>' + arg.originalValue*100 + '%</div>'
                };
            }
        }
    }).dxChart("instance");
}

function showPieChart(data, hint1, hint2, hint3, hint4, hint5) {
    var dataSource = data.dataSource;
    var count = data.sum;
    var reason = data.reason;
    $("#mttrBarChart").dxPieChart({
        palette:palette,
        dataSource: dataSource,
        title: " ",
        legend: {
            orientation: "horizontal",
            itemTextPosition: "center",
            horizontalAlignment: "center",
            verticalAlignment: "bottom",
            columnCount: 4,
            customizeText: function (arg) {
                var legendName = arg.pointName;
                if ($.parseJSON(reason[legendName]).IDLEReason != undefined) {
                    return "IDLE：" + $.parseJSON(reason[legendName]).IDLEReason;
                } else {
                    return hint1 + ':' + $.parseJSON(reason[legendName]).FaultTypeReason;
                }
            }
        },
        "export": {
            enabled: false
        },
        series: [{
            argumentField: "metaId",
            valueField: "time",
            label: {
                visible: true,
                font: {
                    size: 16
                },
                connector: {
                    visible: true,
                    width: 0.5
                },
                customizeText: function (arg) {
                    return arg.percentText;
                }
            }
        }],
        tooltip: {
            enabled: true,
            format: "columns",
            customizeTooltip: function (arg) {
                var r = arg.argumentText;
                var rs = JSON.parse(reason[r]);
                var showReason = rs.IDLEReason === undefined ? rs.FaultTypeReason : rs.IDLEReason;
                return {
                    html: '<div style="text-align:left">' + hint2 + ' :' + showReason + ';</div><div>' + hint3 + ' :' + secondToDate(arg.valueText) + '</div><div>' + hint4 + ' :' + arg.percentText + ';</div><div>' + hint5 + ' :' + secondToDate(count) + '</div>'
                };
            }
        }
    });
}

function showBarChart(data,subTitle) {
    $("#mtbrBarChart").dxChart({
        palette:palette,
        dataSource: data.dataSource,
        commonSeriesSettings: {
            argumentField: "date_id",
            type: "stackedBar"
        },
        valueAxis: {
            label: {
                format: function (value) {
                    return secondToDate(value);
                }
            }
        },
        series: data.series,
        legend: {
            verticalAlignment: "bottom",
            horizontalAlignment: "center",
            itemTextPosition: "bottom"
        },
        title: {
            text: " ",
            subtitle: {
                text: "("+subTitle+")",
                font:{
                    size:14
                }
            }
        },
        "export": {
            enabled: false
        },
        tooltip: {
            enabled: true,
            customizeTooltip: function (arg) {
                return {
                    text: secondToDate(arg.value)
                };
            }
        }
    });
}

function findAllDeviceForChart(message,pc) {
    BYLoadingToast(message, function (dtd) {
        $.ajax({
            url: '/partner/{tenant}/api/v1/device/MTIDS'.replace("{tenant}", getKeyByUrl()),
            type: 'get',
            success: function (data) {
                $("#device").empty();
                dtd.resolve();
                if (data.result != 'SUCCESS') {
                    return;
                }
                if (data.data.length != 0) {
                    $("#device").append($("<option></option>").attr("data-option", "first").attr("selected", "selected").text(pc));
                    $.each(data.data, function (index, device) {
                        var $option = $("<option></option>").attr("data-id", device.deviceId).attr("data-type",device.deviceType).attr("data-model",device.deviceModel).text(device.deviceUniqueId);
                        $("#device").append($option);
                    })
                }
            },
            error: function (e) {
                dtd.resolve();
                console.log(e);
            }
        })
    })
}